package netty.rpc.core;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import netty.rpc.core.HessianSerialization;
import netty.rpc.core.MessageProtocol;

import java.util.List;

/**
 * 字节数组 -> 指定的消息
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2022/5/10 23:21
 */
public class RpcDecoder extends ByteToMessageDecoder {


    private Class<?> targetClass;

    public RpcDecoder(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        if (byteBuf.readableBytes() < MessageProtocol.MESSAGE_HEAD_LENGTH){
            return;
        }

        byteBuf.markReaderIndex();

        // 消息长度
        int messageLength = byteBuf.readInt();

        // 通讯故障 消息体是空
        if (messageLength < MessageProtocol.MESSAGE_BODY_MINIMUM_LENGTH){
            channelHandlerContext.close();
        }

        // 处理拆包问题
        if (byteBuf.readableBytes() < messageLength){
            byteBuf.resetReaderIndex();
            return;
        }

        // 反序列化
        byte[] bytes = new byte[messageLength];
        byteBuf.readBytes(bytes);
        Object object = HessianSerialization.deserialize(bytes, targetClass);
        list.add(object);
    }
}
